package com.valveinspectionsys.routing.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.DbTableName;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.httpserver.DownloadItem;
import com.valveinspectionsys.httpserver.DownloadManager;
import com.valveinspectionsys.httpserver.HttpClientServer;
import com.valveinspectionsys.httpserver.RequestUrl;
import com.valveinspectionsys.povo.ListViewInfo;
import com.valveinspectionsys.routing.db.DeviceRoutingDao;
import com.valveinspectionsys.util.SharedPreferenceUtil;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import android.widget.Toast;

/**
 * 设备巡检主界面
 * @author King
 * 2013-4-23
 */
public class DeviceRoutingMainActivity extends Activity implements OnClickListener {
    public final static int DIALOG = 1;

    public Button button1;//下载
    public Button button2;//巡检
    public Button button3;//查询
    public Button button4;//下载
    public SharedPreferenceUtil sp;
    public DeviceRoutingDao dao;
    public ProgressDialog pd;
	public int total=0;
	public DownloadManager  downma;
	public List<ListViewInfo> list;
	public int listtotal=0;//表册数
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	setContentView(R.layout.device_routing_main);
	sp=new SharedPreferenceUtil(this);
	dao=new DeviceRoutingDao(this, sp.getValue(XmlNameHelper.SqliteName));
	   initView();
	  
	   list=dao.queryAllInfoDeviceList();
	   listtotal=list.size();
	super.onCreate(savedInstanceState);
    }

    //初始化控件
    public void initView(){
	 button1=(Button)findViewById(R.id.device_routing_check);
	 button2=(Button)findViewById(R.id.device_routing_query);
	 button3=(Button)findViewById(R.id.device_routing_upload);
	 button4=(Button)findViewById(R.id.device_routing_down);
	     
	 button1.setOnClickListener(this);
	 button2.setOnClickListener(this);
	 button3.setOnClickListener(this);
	 button4.setOnClickListener(this);
    }
    
    
    @Override
    public void onClick(View v) {
	Intent intent=null;
	 switch (v.getId()) {
	case R.id.device_routing_check:
	  showDialog(DIALOG+1);
	  
	    break;
	case R.id.device_routing_query:
	    if(listtotal==0){
		Toast.makeText(DeviceRoutingMainActivity.this, "没有设备信息不能用此功能", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if(listtotal==1){
		
		intent=new Intent(DeviceRoutingMainActivity.this, DeviceRoutingCheck.class);
		intent.putExtra("devicelistid", list.get(0).getDevicelistid());
	    }else{
		  intent=new Intent(DeviceRoutingMainActivity.this, DeviceRoutingListInfo.class);
	    }
	  
	  //  
	    startActivityForResult(intent, 1);
	   
	    break;
	case R.id.device_routing_upload:
	    intent=new Intent(DeviceRoutingMainActivity.this, DeviceRoutingQueryActivityGroup.class);
	    startActivityForResult(intent, 1);
	    break;
	case R.id.device_routing_down:
	     intent=new Intent(DeviceRoutingMainActivity.this, DeviceUploadMainActivity.class);
	     startActivityForResult(intent, 1);
	    break;
	default:
	    break;
	}
	
    }


    public class download extends AsyncTask<String, Integer, String> {

  	public HttpClientServer server;

  	public ProgressDialog dialog;
  	
  	public int watertotal=0;
  	


  	public download(ProgressDialog dialog) {
  	    this.dialog = dialog;
  	}

  	@Override
  	protected String doInBackground(String... params) {

  	    String userid = sp.getValue(XmlNameHelper.IMEI);
  	  String[]  ss=new String[]{"普通闸阀","蝶阀","消火栓","弹性坐封阀","排气阀","","预留堵板","消火栓和弹性阀"};//设备类型
  	  String[]  ss1=new String[]{"未知","关","1/4开","半开","3/4开","开"};//设备开户状态
  	 
  	    Map<String, String> map = new HashMap<String, String>();
  	    map.put("imei", sp.getValue(XmlNameHelper.IMEI));
  	    map.put("cpId", sp.getValue(XmlNameHelper.userID));
  	    System.out.println("----hppt------------"+params[0]);
  	 String response = server.doPost(map, params[0],true);
  	 //   String response=getFromAssets();
  	    System.out.println("response------------"+response);
  	            //设备册
		    List<ContentValues> devicelist=new ArrayList<ContentValues>();
		    //设备信息
		    List<ContentValues> devicevo=new ArrayList<ContentValues>();		    
		    //图文信息
		    List<ContentValues> tuwen=new ArrayList<ContentValues>();
  	    if (!response.equals("error")) {
  		   dao.delectDeviceAll("1");
  		try {
  		    JSONObject json=new JSONObject(response);
  		    JSONArray devicelistjson=json.getJSONArray("lists");
 		   		  
  		    total=watertotal=0;
  		 
  		    for(int i=0;i<devicelistjson.length();i++){
  			JSONObject jb=devicelistjson.getJSONObject(i);
  			String devicelistid=jb.getString("id");
  			String deviceitem=abc(jb.getString("set"));
  			
  			ContentValues  value =new ContentValues();
  			value.put("devicelistid",devicelistid);
  			
  			//value.put("number", jb.getString("deviceListNumber"));
  			value.put("name", jb.getString("listName"));
  			value.put("deviceitem",deviceitem);
  			String type=jb.getString("periodType");
  			
  			value.put("operationtype",type);
  			devicelist.add(value);
  			JSONArray  devicejson=jb.getJSONArray("valves");
  			
  			//添加设备
  			for(int k=0;k<devicejson.length();k++){
  			    watertotal++;
  			    JSONObject  devicejb=devicejson.getJSONObject(k);
  			  ContentValues devicevalue=new ContentValues();
  			devicevalue.put("deviceid", devicejb.getString("id"));//设备ID
  			devicevalue.put("iscopystatus", "0");
    			devicevalue.put("devicelistid", devicelistid);//所属设备册
    			devicevalue.put("devicecaliber", devicejb.getString("nd"));//公称通径
    			devicevalue.put("devicePressure", devicejb.getString("pn"));//公称压车
    		//	devicevalue.put("inspectionCycle", devicejb.getString("inspectionCycle"));
    		//	devicevalue.put("maintenanceCycle", devicejb.getString("maintenanceCycle"));
    			devicevalue.put("producers", devicejb.getString("manufacturer"));//生产商
    			devicevalue.put("productionDate", devicejb.getString("manufactureDate"));//生产日期
    			String usestatus=devicejb.getString("useStatus");
    			String str="拆除";
    			if(usestatus.equals("0")){
    			    str="在用";
    			}else if(usestatus.equals("1")){
    			    str="安装";
    			}
    			devicevalue.put("useStatus",str );//使用状态
    			devicevalue.put("openStatus", ss1[devicejb.getInt("openStatus")]);//开启状态
    			devicevalue.put("devicetype", ss[devicejb.getInt("type")]);//设备类型()
    			devicevalue.put("operationtype",type);//0周期巡检  1灵时巡检
    					
    			devicevalue.put("devicesort", devicejb.getInt("inspectListOrder"));//设备在设备册的顺序    			    			
    			JSONObject  vmp=devicejb.getJSONObject("vmp");
    			devicevalue.put("devicenumber", vmp.getString("valveNumber"));//设备编号
    			devicevalue.put("InstallationDate", vmp.getString("intallDate"));//安装日期
    			devicevalue.put("deviceadds", vmp.getString("addr"));//安装地址
    			devicevalue.put("devicelib", vmp.getString("lib"));//来自设备库
    			devicevalue.put("place", vmp.getString("place"));//所属场所
    			devicevalue.put("area", vmp.getString("area"));//所属片区
    			devicevalue.put("netWork", vmp.getString("netWork"));//所属网短
    	                devicevalue.put("deviceitem", deviceitem);
    			String  latitude=vmp.getString("lat");
    			if(!TextUtils.isEmpty(latitude)&&!latitude.equals("null")){
    			devicevalue.put("latitude", vmp.getDouble("lat"));
    			devicevalue.put("longitude", vmp.getDouble("lon"));
    			}else{
    			devicevalue.put("latitude",0.0);
    			devicevalue.put("longitude", 0.0);
    			}
    		        String rfid=vmp.getString("rfid");
    		         devicevalue.put("RFIDnumber", rfid);
    			if(TextUtils.isEmpty(rfid)||rfid.equals("null")){
    			devicevalue.put("bandingstatus", "2");
    			}else{
    			devicevalue.put("bandingstatus", "3");
    			}
    			
    			JSONArray  tuwenjson=devicejb.getJSONArray("images");
    			if(tuwenjson!=null&&tuwenjson.length()>0){
    			  
    			    for(int n=0;n<tuwenjson.length();n++){
    				 JSONObject   tuwenjb=tuwenjson.getJSONObject(n);
    				 ContentValues  tvalue=new ContentValues();
    				 String isimg=tuwenjb.getString("type").equals("0")?"1":"2";
    				 tvalue.put("othernumber", tuwenjb.getString("valveId"));
    				 tvalue.put("isimg", isimg);
    				 tvalue.put("waterlistid", devicelistid);
    				 tvalue.put("type", type);
    				 if(isimg.equals("1")){
    				  tvalue.put("isdownload", "0");
    				 }else{
    				 tvalue.put("isdownload", "1");
				  tvalue.put("imgpath", tuwenjb.getString("details"));
    				   
    				 }
    				 tvalue.put("imgwebname", tuwenjb.getString("details"));
    				 System.out.println("---------isimage--------"+isimg+"---------"+tuwenjb.getString("details"));
    				 tvalue.put("Sortnumber", tuwenjb.getString("ordre"));
    				 tuwen.add(tvalue);
    			    }
    			     
    			}
    			
    			
    		        devicevo.add(devicevalue);
    		     
    		      publishProgress(i + 1);
  			}
  		    }
  		                      dao.insertALL(devicelist, DbTableName.DEVICELIST);
  		boolean b=    dao.insertALL(devicevo, DbTableName.DEVICEINFO);
  		                       dao.insertALL(tuwen, DbTableName.NAVIGATION);
  		    if(b){
  			return "suess";
  		    }else{
  			return "error";
  		    }
  		} catch (JSONException e) {
  		    e.printStackTrace();

  		   return "error";
  		
  		}

  	    }
  	    return "error";

  	}

  	@Override
  	protected void onPreExecute() {
  	    server = new HttpClientServer(DeviceRoutingMainActivity.this);
  	 

  	    dialog.setMax(100);
  	    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  	    dialog.setTitle("下载数据中.......");
  	    dialog.setCancelable(false);
  	    dialog.show();

  	}

  	@Override
  	protected void onProgressUpdate(Integer... values) {
  	    System.out.println("onprogress------>" + (int) ((float) total / values[0] * 100));
  	    System.out.println("----------values---" + values[0]);
  	    dialog.setProgress((int) ((float) values[0] / total * 100));
  	}

  	@Override
  	protected void onPostExecute(String result) {

  	    dialog.cancel();
  	    if (TextUtils.isEmpty(result)) {
  		Toast.makeText(DeviceRoutingMainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
  		
  	    } else if (result.equals("error")) {
  		Toast.makeText(DeviceRoutingMainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
  	    } else {
  		Toast.makeText(DeviceRoutingMainActivity.this, "下载成功,共下载抄表数据:" + watertotal, Toast.LENGTH_SHORT).show();
  		downTuwen();
  		
  	    }

  	}

      }

  //读取assets下文件流
    public String getFromAssets(){
    	InputStreamReader inputReader=null;
    	 BufferedReader bufReader =null;
    	  String line="";
          String Result="";
    	try {
    	     inputReader = new InputStreamReader( getResources().getAssets().open("rount.text") );
    	     bufReader = new BufferedReader(inputReader);
          
            while((line = bufReader.readLine()) != null){
        	   Result += line;
            }
    	} catch (IOException e) {
    	    
    	    e.printStackTrace();
    	}finally{
    	    if(bufReader!=null){
    		try {
    		    bufReader.close();
    		} catch (IOException e) {
    		 
    		    e.printStackTrace();
    		}
    	    }
    	    if(inputReader!=null){
    		try {
    		    inputReader.close();
    		} catch (IOException e) {
    		 
    		    e.printStackTrace();
    		}
    	    }
    	} 

    	return Result;
    	
    }
    
    public String abc(String info){
	String str="";
	for(int i=0;i<8;i++){
	    str=str+info.charAt(i)+",";
	}
	return str.substring(0, str.length()-1);
    }
    

    // 下载图文数据
    public void downTuwen() {
	System.out.println("-----------开始 下载图片-------------");
	if(downma==null){
	    downma=new DownloadManager(this, myHandler, dao.getDb());
	}

	List<DownloadItem> list = dao.queryNoDown();
	
	if (list == null || list.size() < 1) {
	   
	    return;
	}
	
	pd = new ProgressDialog(this);
	pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	pd.setTitle("下载图文中.......");
	pd.setCancelable(false);
	pd.setButton("取消", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		pd.dismiss();
		downma.stop();
		
	    }
	});
	pd.setButton2("放弃下载", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		pd.dismiss();
		downma.stop();
	
		return;
	    }
	});
	
	
	downma.start();
	pd.setMax(list.size());
	for (int i = 0; i < list.size(); i++) {
	    downma.addTask(list.get(i));
	}
	pd.show();
    }
    
    Handler myHandler = new Handler() {

  	@Override
  	public void handleMessage(Message msg) {
  	    if (msg.what == 0) {
  		
  		pd.setProgress(pd.getProgress() + 1);
  		if (pd.getMax() == pd.getProgress()) {
                      pd.dismiss();
  		     Toast.makeText(DeviceRoutingMainActivity.this, "下载图文成功", Toast.LENGTH_SHORT).show();
  		
  		    downma.stop();
  		   
  		}
  	    } else if (msg.what == 1) {
//  		pd.dismiss();
//  		downma.stop();
//  		adapter.downUpdateView(postion, waterlistid);	

  	    } else if (msg.what == 2) {
  		
  		pd.setProgress(pd.getProgress() + 1);
  		if (pd.getMax() == pd.getProgress()) {
 
  		    downma.stop();
  		   
  		}
  	    }
  	    super.handleMessage(msg);
  	}

      };
      
      @Override
      protected Dialog onCreateDialog(int id) {
  	Dialog dialog = null;
  	switch (id) {
  	
  	case DIALOG + 1:
  	    Builder builder1 = new android.app.AlertDialog.Builder(this);
  	    // 设置对话框的图标
  	    builder1.setIcon(R.drawable.buttondraw);
  	    builder1.setMessage("确定下载新设备册？");
  	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

  		@Override
  		public void onClick(DialogInterface dialog, int which) {
  		  
  		     pd=new ProgressDialog(DeviceRoutingMainActivity.this);
  		    download down=new download(pd);
  		    down.execute(RequestUrl.DOWNLOAD_ROUNTING_DEVICE);
  		}
  	    });
  	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

  		@Override
  		public void onClick(DialogInterface dialog, int which) {

  		}
  	    });
  	    // 创建一个单选按钮对话框
  	    dialog = builder1.create();
  	    break;

  
  	}

  	return dialog;
      }
      
    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }

}
